<template>
  <div class="article-comments">
    <!-- 评论列表 -->
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
      :immediate-check="false"
    >
      <comment-item
        v-for="(item, index) in list"
        :key="index"
        :item="item"
        @click_reply="$emit('click_reply', $event)"
      />
    </van-list>
    <!-- 评论列表 -->

    <!-- 发布评论 -->
    <!-- <van-cell-group class="publish-wrap">
      <van-field clearable placeholder="请输入评论内容">
        <van-button slot="button" size="mini" type="info">发布</van-button>
      </van-field>
    </van-cell-group> -->
    <!-- /发布评论 -->
  </div>
</template>

<script>
import { getComments } from "@/api/comment";
import CommentItem from "./comment-item.vue";

export default {
  name: "commentList",
  props: {
    sourceId: {
      type: [Number, String, Object],
      required: true
    },
    list: {
      type: Array,
      required: true
    },
    type: {
      type: String,
      default: "a"
    }
  },
  components: {
    CommentItem
  },
  data() {
    return {
      loading: false, // 上拉加载更多的 loading
      finished: false, // 是否加载结束
      offset: null,
      limit: 10
    };
  },
  created() {
    this.loading = true;
    this.onLoad();
  },
  methods: {
    async onLoad() {
      try {
        let { data: res } = await getComments({
          type: this.type,
          source: this.sourceId.toString(),
          offset: this.offset,
          limit: this.limit
        });
        // console.log(res);
        this.list.push(...res.data.results);
        this.loading = false;
        this.$emit("update-count", res.data.total_count);
        if (!res.data.last_id) {
          this.finished = true;
        } else {
          this.offset = res.data.last_id;
        }
      } catch (error) {
        this.$toast.fail("获取评论数据失败");
      }
    }
  }
};
</script>

<style scoped lang="less">
.publish-wrap {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
}

.van-list {
  margin-bottom: 45px;
}
</style>
